package com.kaixinff.kaixin001.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.kaixinff.kaixin001.util.KXClient;
import com.kaixinff.kaixin001.util.KXUtil;
import com.kaixinff.kaixin001.util.RegStep;
import com.kaixinff.name.NameUtil;
import com.kaixinff.name.User;
import com.kaixinff.net.HttpClient;
import com.kaixinff.net.NameValuePair;

@SuppressWarnings("serial")
public class ConfirmFriendRequestServlet extends HttpServlet {
	private static final String SYS_URL = KXUtil.HOST_URL + "/msg/sys.php?type=1";
	private static final String groups = "100";
	private static String allGroups;
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/html; charset=" + KXUtil.CHARSET);
		String email = KXUtil.getMainUserEmail();
		KXClient client = KXClient.getInstance(email);
		if (!client.isLogined()) {
			List<String> emails = new ArrayList<String>();
			emails.add(email);
			LoginServlet.initPage(emails, resp);
		} else {
			confirm(client);
		}
	}
	
	private void confirm(HttpClient client) throws IOException {
		String html = client.doGet(SYS_URL, null).getContent();
		String[] strs = html.split("<div class=\"l\"><b>好友请求：</b></div>");
		Pattern p = Pattern.compile("javascript[:]agreefriend[(](\\d+?), (\\d+?)[)];");
		List<User> users = KXUtil.getUsers();
		Map<String, User> userMap = KXUtil.getUserMap();
		try {
			for (int i = 0, n = strs.length; i < n; i++) {
				if (strs[i].indexOf("“哈罗小饭，我是") > -1) {
					Matcher m = p.matcher(strs[i]);
					if (m.find()) {
						String fuid = m.group(1);
						String smid = m.group(2);
						String email = KXUtil.getEmail(fuid);
						if (email != null) {
							confirm(client, fuid, smid, userMap.get(email));
						}
					}
				}
			}
		} finally {
			KXUtil.saveUsers(users);
		}
	}
	
	private String getAllGroups(HttpClient client, String fuid, String smid) throws IOException {
		if (allGroups == null) {
			String url = KXUtil.HOST_URL + "/friend/editfriend_dialog.php?smid=" + smid + "&fuid=" + fuid;
			String html = client.doGet(url, SYS_URL).getContent();
			Pattern p = Pattern.compile("[{]\"checked\"[:]\".+?\",\"type\"[:]\".+?\",\"name\"[:]\"(.+?)\"[}]");
			Matcher m = p.matcher(html);
			StringBuffer sb = new StringBuffer();
			while (m.find()) {
				String group = KXUtil.toUTF(m.group(1));
				sb.append(",");
				sb.append(group);
			}
			allGroups = sb.substring(1);
		}
		return allGroups;
	}
	
	private void confirm(HttpClient client, String fuid, String smid, User user) throws IOException {
		String url = KXUtil.HOST_URL + "/friend/editfriend.php";
		NameValuePair[] params = new NameValuePair[]{
				new NameValuePair("fuid", fuid),
				new NameValuePair("byname", ""),
				new NameValuePair("memo", ""),
				new NameValuePair("groups", groups),
				new NameValuePair("allgroups", getAllGroups(client, fuid, smid)),
				new NameValuePair("start", "0"),
				new NameValuePair("sysmsgtype", "1"),
				new NameValuePair("from", "sysmsg"),
				new NameValuePair("smid", smid)};
		client.doPost(url, SYS_URL, params);
		
		url = KXUtil.HOST_URL + "/msg/sysdel.php";
		params = new NameValuePair[]{
				new NameValuePair("smid", smid),
				new NameValuePair("start", "0")};
		client.doPost(url, SYS_URL, params);
		
		HttpClient client2 = KXClient.getInstance(user.getId());
		String html = client2.doGet(SYS_URL, null).getContent();
		if (html.indexOf("editFriend(" + KXUtil.getMainUserUid() + ",") > -1) {
			System.out.println("Confirm " + user.getId());
			user.addStep(RegStep.ADD_FRIEND_CONFIRM);
		}
	}

}
